package com.atguigu.xuexiplus.controller;

import com.atguigu.xuexiplus.entity.Subject;
import com.atguigu.xuexiplus.result.Result;
import com.atguigu.xuexiplus.service.SubjectService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 学科控制器
 */
@RestController
@RequestMapping("/api/subjects")
@CrossOrigin(origins = "*")
public class SubjectController {

    @Autowired
    private SubjectService subjectService;

    /**
     * 获取所有启用的学科
     */
    @GetMapping
    public Result<List<Subject>> getAllSubjects() {
        try {
            List<Subject> subjects = subjectService.getActiveSubjects();
            System.out.println("获取到学科数量: " + subjects.size());
            return Result.success(subjects);
        } catch (Exception e) {
            System.err.println("获取学科列表失败: " + e.getMessage());
            e.printStackTrace();
            return Result.error("获取学科列表失败: " + e.getMessage());
        }
    }

    /**
     * 根据ID获取学科
     */
    @GetMapping("/{id}")
    public Result<Subject> getSubjectById(@PathVariable Long id) {
        Subject subject = subjectService.getSubjectById(id);
        if (subject == null) {
            return Result.error("学科不存在");
        }
        return Result.success(subject);
    }

    /**
     * 测试学科接口
     */
    @GetMapping("/test")
    public Result<String> test() {
        return Result.success("学科接口正常工作");
    }
}

